package bal.android.usuario;

import bal.android.BalActivity;
import bal.android.ConexaoServidor;
import bal.android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CadastrarUsuarioActivity extends Activity {
	
	Button voltar, cadastrar;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastrar_usuario);
		
		cadastrar = (Button) findViewById(R.id.buttonCadastrarUsuario);
		cadastrar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cadastrarUsuario();
			}
		});
		
		voltar = (Button) findViewById(R.id.buttonVoltar);
		voltar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				telaInicial();
			}
		});
	}
	
	private void cadastrarUsuario() {
		String nome = ((EditText) findViewById(R.id.nome)).getText().toString();
		String login = ((EditText) findViewById(R.id.login)).getText().toString();
		String senha = ((EditText) findViewById(R.id.senha)).getText().toString();
		String senhaConfirmacao = ((EditText) findViewById(R.id.senhaConfirmacao)).getText().toString();
		
		String[] keys = { "nome", "login", "senha", "senhaConfirmacao" };
		String[] values = { nome, login, senha, senhaConfirmacao };

		String response = ConexaoServidor.execute("CadastrarUsuarioServlet", keys, values);
		
		if (response.equals("sucesso")) {
			Intent intent = new Intent(this, BalActivity.class);
			startActivity(intent);
			this.finish();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false)
					.setNeutralButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});

			if (response.equals("erro_banco")) {
				builder.setMessage("Um erro ocorreu no banco de dados.");
			} else {
				builder.setMessage(response);
			}

	        AlertDialog alert = builder.create();
	        alert.show();
		}
	}
	
	public void telaInicial() {
		Intent intent = new Intent(this, BalActivity.class);
		startActivity(intent);
		this.finish();
	}
	
}
